<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    use HasFactory;

    /**
     * 与模型关联的数据表。
     *
     * @var string
     */
    protected $table = 'settings';
    /**
     *为模型指定一个主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     *为模型指定一个连接名称
     *
     * @var string
     */
    protected $fillable = ['code', 'value'];

    public $timestamps = false;

    /**
     * 添加数据
     * @param null $data
     * @param null $code
     * @return bool
     */
    public static function set($value = null, $code = null)
    {
        if (!$code) {
            return false;
        }

        return self::updateOrCreate(
            [
                'code' => $code,
            ],
            [
                'value' => $value,
                'code' => $code,
            ]
        );
    }


    /**
     * 根据code 获取对应的数据
     */
    public static function get($code)
    {
        $query = ['code' => $code];

        $model = self::where($query)->select('code', 'value')->first();

        return $model ? $model->toArray() : null;
    }
}
